//----------------------------------------------------------------------------//
// File: main.c
// Author: Felipe Castro
// Date: 02/05/2010
// Description:
//   Main Function
//----------------------------------------------------------------------------//

//----------------------//
// INCLUDES             //
//----------------------//
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "rs232.h"
#include "globals.h"
#include "solveF1Commands.h"
#include "bluetoothManager.h"


unsigned char serialBuf[SERIAL_BUFFER_SIZE];


//-----------------------------------------------//
// Thread Handle                                 //
//-----------------------------------------------//

void *PrintHello(void *threadid) {
    unsigned char tempChar = 0;
    long tid;
    tid = (long) threadid;
    static unsigned char contBuf = 0;


    for (;;) {
        if (PollComport(0, &tempChar, 1) != 0) {
            if (tempChar != '+') {
                serialBuf[contBuf] = tempChar;
                contBuf++;
                if (tempChar == '\n') {
                    contBuf = 0;
                    solveF1Command(serialBuf);
                }
                fflush(stdout);
            }
        }
    }

    pthread_exit(NULL);
}

//-----------------------------------------------//
// Main                                          //
//-----------------------------------------------//

int main(int argc, char *argv[]) {
    pthread_t threads[NUM_THREADS];
    unsigned char tempChar;
    int rc;
    long t;

    printf("--------- F1NAV_C OpenSource ---------\n\n");

    printf("[s]Serial [b]Bluetooth\n");
    scanf("%s", &tempChar);

    if (tempChar == 's') {

        if (OpenComport(SERIAL_COMPORT, SERIAL_BAUDRATE) != 0) {
            printf(" - ERROR OPENING PORT - \n");
        } else {

            for (t = 0; t < NUM_THREADS; t++) {
                printf("Creating read thread\n\n");
                rc = pthread_create(&threads[t], NULL, PrintHello, (void *) t);
                if (rc) {
                    printf("Error creating thread => pthread_create() error %d\n", rc);
                    exit(-1);
                }
            }
            pthread_exit(NULL);
        }
    }
    else if(tempChar=='b'){
        printf("--------------------------------------------\n");
        printf("Finding bluetooth devices\n\n");
        findBluetoothDevices();
    }


}



